<template>
  <view class="container">
    <view class="header">
      <text class="title">{{ isEditMode ? '编辑历史记录' : '添加历史记录' }}</text>
    </view>
    
    <view class="form-container">
      <!-- 投资类别 -->
      <view class="form-item">
        <text class="label">投资类别</text>
        <picker v-model="category" :range="categories" @change="onCategoryChange">
          <view class="date-display">{{ category }}</view>
        </picker>
      </view>
      
      <!-- 人民币输入框 -->
      <view class="form-item">
        <text class="label">人民币金额 (CNY)</text>
        <input 
          class="input" 
          type="digit" 
          v-model="cnyAmount" 
          placeholder="请输入人民币金额"
        />
      </view>
      
      <!-- 日期选择 - 隐藏显示但保持日期值自动填充 -->
      <view class="form-item" style="display: none;">
        <text class="label">日期</text>
        <picker mode="date" :value="currentDate" :start="'2000-01-01'" :end="currentDate" @change="onDateChange">
          <view class="date-display">
            {{ formattedDate }}
          </view>
        </picker>
      </view>
      
      <!-- 定存相关字段 - 条件显示 -->
      <view v-if="category === '定存'" class="form-item">
        <text class="label">起始日期</text>
        <picker mode="date" :value="depositStartDate" :start="'2000-01-01'" :end="currentDate" @change="onDateChange">
          <view class="date-display">{{ depositStartDate || '请选择起始日期' }}</view>
        </picker>
      </view>
      
      <view v-if="category === '定存'" class="form-item">
        <text class="label">定存时长 (月)</text>
        <input 
          class="input" 
          type="number" 
          v-model="depositDuration" 
          placeholder="请输入定存时长（月）"
        />
      </view>
      
      <view v-if="category === '定存'" class="form-item">
        <text class="label">年利率 (%)</text>
        <input 
          class="input" 
          type="digit" 
          v-model="depositRate" 
          placeholder="请输入年利率（例如：2.6）"
        />
      </view>
      
      <!-- 保存按钮 -->
      <button class="save-button" @click="saveRecord">保存记录</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { API_BASE_URL } from '../../utils/config';
import { basePost, basePut } from '../../utils/api';

const router = useRouter();
const route = useRoute();
const cnyAmount = ref('');
const isEditMode = ref(false);
const recordId = ref(null);
const currentDate = ref('');
const category = ref('货币基金');
const categories = ['货币基金', '黄金', '定存', '虚拟币'];

// 定存相关字段
const depositStartDate = ref('');
const depositDuration = ref('');
const depositRate = ref('');

const formattedDate = computed(() => {
  return formatDate(currentDate.value);
});

// 初始化页面数据
onMounted(() => {
  // 设置当前日期
  const today = new Date();
  currentDate.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  
  // 检查URL中是否有category参数，如果有则设置（并解码）
  if (route.query.category) {
    category.value = decodeURIComponent(route.query.category);
    
    // 如果从URL传入的是定存类别，自动设置起始日期
    if (category.value === '定存' && !depositStartDate.value) {
      depositStartDate.value = currentDate.value;
    }
  }
  
  // 检查是否是编辑模式
  if (route.query.mode === 'edit') {
    isEditMode.value = true;
    recordId.value = route.query.id;
    
    // 预填充表单数据
    if (route.query.cny) {
      cnyAmount.value = route.query.cny;
    }
    if (route.query.date) {
      currentDate.value = route.query.date;
    }
    // 预填充定存相关数据（如果是编辑模式且有相关参数）
    if (route.query.deposit_start_date) {
      depositStartDate.value = route.query.deposit_start_date;
    }
    if (route.query.deposit_duration) {
      depositDuration.value = route.query.deposit_duration;
    }
    if (route.query.deposit_rate) {
      depositRate.value = route.query.deposit_rate;
    }
  }
});

// 格式化日期为年-月-日格式
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 处理投资类别选择事件
const onCategoryChange = (e) => {
  // 更新类别值
  category.value = categories[e.detail.value];
  
  // 如果选择了定存，自动设置起始日期为当前日期
  if (category.value === '定存' && !depositStartDate.value) {
    depositStartDate.value = currentDate.value;
  }
};

// 处理日期选择事件
const onDateChange = (e) => {
  // 如果是从日期选择器触发的事件，则更新当前日期
  if (e.detail.value) {
    currentDate.value = e.detail.value;
  }
};

// 保存记录
const saveRecord = async () => {
  // 验证输入
  if (!cnyAmount.value) {
    uni.showToast({
      title: '请输入人民币金额',
      icon: 'none'
    });
    return;
  }
  
  // 定存类别的额外验证
  if (category.value === '定存') {
    if (!depositStartDate.value) {
      uni.showToast({
        title: '请选择定存起始日期',
        icon: 'none'
      });
      return;
    }
    if (!depositDuration.value || isNaN(parseInt(depositDuration.value))) {
      uni.showToast({
        title: '请输入有效的定存时长',
        icon: 'none'
      });
      return;
    }
    if (!depositRate.value || isNaN(parseFloat(depositRate.value))) {
      uni.showToast({
        title: '请输入有效的年利率',
        icon: 'none'
      });
      return;
    }
  }
  
  // 格式化保存的数据
  const recordData = {
    date: currentDate.value,
    cny: parseFloat(cnyAmount.value),
    category: category.value,
    // 为向后兼容添加默认值
    usd: 0,
    exchange_rate: 0
  };
  
  // 添加定存相关数据
  if (category.value === '定存') {
    recordData.deposit_start_date = depositStartDate.value;
    recordData.deposit_duration = parseInt(depositDuration.value);
    recordData.deposit_rate = parseFloat(depositRate.value);
  }
  
  try {
    let res;
    
    // 根据模式选择请求方法，使用不带token验证的API
    if (isEditMode.value) {
      res = await basePut(`/investment-history/${recordId.value}`, recordData);
    } else {
      res = await basePost('/investment-history', recordData);
    }
    
    // 接受200和201作为成功状态码
    if ((res.statusCode === 200 || res.statusCode === 201) && res.data.success) {
      // 显示成功提示
      uni.showToast({
        title: isEditMode.value ? '修改成功' : '添加成功',
        icon: 'success',
        success: () => {
          // 延迟返回上一个页面
          setTimeout(() => {
            router.back();
          }, 1500);
        }
      });
    } else {
      uni.showToast({
        title: res.data?.error || (isEditMode.value ? '修改失败' : '添加失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存记录失败:', error);
    if (error.message !== '未登录') {
      uni.showToast({
        title: '网络错误，保存失败',
        icon: 'none'
      });
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.form-container {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.input {
  width: 100%;
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 16px;
  font-size: 16px;
  box-sizing: border-box;
}

.rate-display {
  width: 100%;
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 16px;
  font-size: 16px;
  display: flex;
  align-items: center;
  background-color: #f9f9f9;
  color: #333;
  box-sizing: border-box;
}

.date-display {
  width: 100%;
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 16px;
  font-size: 16px;
  display: flex;
  align-items: center;
  background-color: #f9f9f9;
  color: #333;
  box-sizing: border-box;
}

.save-button {
  width: 100%;
  height: 48px;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
}

.save-button:active {
  background-color: #096dd9;
}
</style>